<template>
	<view class="order-list-container">
		<!-- 订单状态筛选 -->
		<u-tabs :bar-style="!status?barStyle:{}" ref="tabs1" v-model="status" :list="tabs" :is-scroll="false"></u-tabs>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y @scrolltolower="loadMoreOrders" :refresher-triggered="refreshing"
			refresher-enabled @refresherrefresh="onRefresh">
			<!-- 订单列表 -->
			<view v-if="orders.length > 0">
				<view class="order-item" v-for="order in orders" :key="order.id" @click="viewOrderDetail(order.id)">
					<view class="order-header">
						<view class="order-shop">
							<u-icon name="home" size="28" color="#666" class="shop-icon"></u-icon>
							<text class="shop-name">{{ order.shopName }}</text>
						</view>
						<view class="order-status" :class="[getStatusClass(order.status)]">
							{{ getStatusText(order.status) }}</view>
					</view>

					<view class="order-content">
						<view class="order-goods">
							<view class="goods-item" v-for="(item, index) in order.items" :key="index">
								<image class="goods-image" :src="item.image" mode="aspectFill"></image>
								<view class="goods-info">
									<view class="goods-name">{{ item.name }}</view>
									<view class="goods-spec" v-if="item.specification">{{ item.specification }}</view>
								</view>
								<view class="goods-right">
									<view class="goods-price">¥{{ formatMoney(item.price) }}</view>
									<view class="goods-quantity">x{{ item.quantity }}</view>
								</view>
							</view>
						</view>

						<view class="order-summary">
							<view class="order-time">{{ formatDateTime(order.createTime, 'YYYY-MM-DD HH:mm') }}</view>
							<view class="order-amount">
								<text>共{{ getTotalItems(order.items) }}件商品，</text>
								<text>合计：</text>
								<text class="price-symbol">￥</text>
								<text class="price-value">{{ formatMoney(order.totalAmount) }}</text>
							</view>
						</view>
					</view>

					<view class="order-footer">
						<view class="order-btns">
							<block v-if="order.status === 'pending_payment'">
								<u-button type="default" size="mini" plain @click.stop="cancelOrder(order.id)"
									:customStyle="{borderColor: '#999', color: '#999'}">取消订单</u-button>
								<u-button type="primary" size="mini" @click.stop="payOrder(order.id, order.totalAmount)"
									:customStyle="{background: 'linear-gradient(90deg, #fa436a, #F56C6C)', border: 'none'}">去支付</u-button>
							</block>
							<block v-if="order.status === 'paid'">
								<u-button type="primary" size="mini" plain @click.stop="viewOrderDetail(order.id)"
									:customStyle="{borderColor: '#fa436a', color: '#fa436a'}">查看详情</u-button>
							</block>
							<block v-if="order.status === 'completed'">
								<u-button type="primary" size="mini" plain @click.stop="viewOrderDetail(order.id)"
									:customStyle="{borderColor: '#fa436a', color: '#fa436a'}">查看详情</u-button>
							</block>
							<block v-if="order.status === 'cancelled'">
								<u-button type="primary" size="mini" plain @click.stop="viewOrderDetail(order.id)"
									:customStyle="{borderColor: '#fa436a', color: '#fa436a'}">查看详情</u-button>
							</block>
						</view>
					</view>
				</view>

				<!-- 加载更多 -->
				<view v-if="hasMore" class="loading-more">
					<u-loadmore :status="loadMoreStatus"></u-loadmore>
				</view>
			</view>

			<!-- 无数据提示 -->
			<view v-else class="no-data">
				<u-empty text="暂无订单数据" mode="order"></u-empty>
				<view class="empty-action">
					<u-button type="primary" size="medium" @click="goToMenu"
						:customStyle="{background: 'linear-gradient(90deg, #fa436a, #F56C6C)', border: 'none'}">去点餐</u-button>
				</view>
			</view>
		</scroll-view>

		<!-- 取消订单确认弹窗 -->
		<u-modal v-model="showCancelModal" content="确定要取消该订单吗？" :show-cancel-button="true" confirm-text="确定"
			cancel-text="取消" @confirm="confirmCancelOrder"></u-modal>
	</view>
</template>

<script>
	import {
		orderStatus
	} from '@/common/utils/mock.js';
	import {
		formatMoney,
		formatDateTime,
		showToast,
		showLoading,
		hideLoading
	} from '@/common/utils/util.js';

	export default {
		data() {
			return {
				barStyle:{
					transform: 'translate(54rpx, -100%)'
				},
				status: '',
				tabs: [{
						name: '全部',
						status: ''
					},
					{
						name: '待支付',
						status: orderStatus.PENDING_PAYMENT
					},
					{
						name: '已支付',
						status: orderStatus.PAID
					},
					{
						name: '已完成',
						status: orderStatus.COMPLETED
					},
					{
						name: '已取消',
						status: orderStatus.CANCELLED
					}
				],
				activeTabIndex: 0,
				orders: [],
				mockOrders: [{
						id: '10001',
						shopId: '1',
						shopName: '微餐饮门店(望京店)',
						status: 'pending_payment',
						createTime: new Date().getTime() - 3600000, // 1小时前
						totalAmount: 45.8,
						items: [{
							id: '101',
							name: '香辣小龙虾',
							price: 38.8,
							quantity: 1,
							specification: '麻辣味',
							image: 'https://img.alicdn.com/imgextra/i4/6000000001401/O1CN01UQnMAI1MScRlAlnf7_!!6000000001401-0-tbvideo.jpg'
						}]
					},
					{
						id: '10002',
						shopId: '1',
						shopName: '微餐饮门店(国贸店)',
						status: 'paid',
						createTime: new Date().getTime() - 86400000, // 1天前
						totalAmount: 99.6,
						items: [{
								id: '201',
								name: '黄金炒饭',
								price: 28.8,
								quantity: 2,
								specification: '微辣',
								image: 'https://img.alicdn.com/imgextra/i1/6000000004006/O1CN01FgGXIy1esZVB2AnL9_!!6000000004006-0-tbvideo.jpg'
							},
							{
								id: '202',
								name: '宫保鸡丁',
								price: 42,
								quantity: 1,
								specification: '',
								image: 'https://img.alicdn.com/imgextra/i2/6000000007798/O1CN01dVYpEK28OPsOKK34b_!!6000000007798-0-tbvideo.jpg'
							}
						]
					},
					{
						id: '10003',
						shopId: '1',
						shopName: '微餐饮门店(三里屯店)',
						status: 'completed',
						createTime: new Date().getTime() - 172800000, // 2天前
						totalAmount: 138.8,
						items: [{
								id: '301',
								name: '水煮鱼片',
								price: 58.8,
								quantity: 1,
								specification: '特辣',
								image: 'https://img.alicdn.com/imgextra/i1/6000000000810/O1CN01L0DTiY1HyEtOHjvKz_!!6000000000810-0-tbvideo.jpg'
							},
							{
								id: '302',
								name: '麻婆豆腐',
								price: 32,
								quantity: 1,
								specification: '',
								image: 'https://img.alicdn.com/imgextra/i2/6000000004824/O1CN01YfYjSH1k3UWd5TkF5_!!6000000004824-0-tbvideo.jpg'
							},
							{
								id: '303',
								name: '白米饭',
								price: 4,
								quantity: 2,
								specification: '',
								image: 'https://img.alicdn.com/imgextra/i4/6000000000214/O1CN01AH1Yov1DdtsMpesxJ_!!6000000000214-0-tbvideo.jpg'
							}
						]
					},
					{
						id: '10004',
						shopId: '1',
						shopName: '微餐饮门店(朝阳店)',
						status: 'cancelled',
						createTime: new Date().getTime() - 259200000, // 3天前
						totalAmount: 78.6,
						items: [{
							id: '401',
							name: '北京烤鸭',
							price: 78.6,
							quantity: 1,
							specification: '半只',
							image: 'https://img.alicdn.com/imgextra/i1/6000000002345/O1CN01BShFqr1SjT11vRnjw_!!6000000002345-0-tbvideo.jpg'
						}]
					}
				],
				page: 1,
				pageSize: 10,
				hasMore: true,
				loadMoreStatus: 'loadmore',
				refreshing: false,
				showCancelModal: false,
				cancelOrderId: ''
			};
		},

		onLoad() {
			// 使用假数据填充
			this.loadMockData();
		},

		onShow() {
			// 如果从其他页面返回，刷新数据
			this.onRefresh();
		},

		methods: {
			formatMoney,
			formatDateTime,

			// 加载模拟数据
			loadMockData() {
				// 根据当前选中的标签过滤数据
				const status = this.tabs[this.activeTabIndex].status;

				if (status) {
					this.orders = this.mockOrders.filter(order => order.status === status);
				} else {
					// 全部
					this.orders = [...this.mockOrders];
				}

				// 模拟异步加载
				this.refreshing = false;
				this.loadMoreStatus = 'nomore';
				this.hasMore = false;
			},

			// 切换标签
			switchTab(index) {
				if (this.activeTabIndex === index) return;
				this.activeTabIndex = index;
				this.page = 1;
				this.orders = [];
				this.hasMore = true;
				this.loadMoreStatus = 'loadmore';
				this.loadMockData();
			},

			// 加载订单
			async loadOrders(loadMore = false) {
				// 使用假数据，直接调用loadMockData
				this.loadMockData();
			},

			// 下拉刷新
			onRefresh() {
				this.refreshing = true;
				setTimeout(() => {
					this.loadMockData();
				}, 1000);
			},

			// 加载更多
			loadMoreOrders() {
				if (this.hasMore && this.loadMoreStatus !== 'loading') {
					this.loadMoreStatus = 'loading';
					setTimeout(() => {
						this.loadMoreStatus = 'nomore';
						this.hasMore = false;
					}, 1000);
				}
			},

			// 查看订单详情
			viewOrderDetail(id) {
				showToast('查看订单详情: ' + id);
				// 实际开发时跳转到详情页
				// uni.navigateTo({
				//   url: `/pages/order/detail?id=${id}`
				// });
			},

			// 取消订单
			cancelOrder(id) {
				this.cancelOrderId = id;
				this.showCancelModal = true;
			},

			// 确认取消订单
			async confirmCancelOrder() {
				if (!this.cancelOrderId) return;

				showLoading('取消订单中...');

				// 模拟取消订单
				setTimeout(() => {
					// 在模拟数据中找到订单并修改状态
					const orderIndex = this.mockOrders.findIndex(o => o.id === this.cancelOrderId);
					if (orderIndex !== -1) {
						this.mockOrders[orderIndex].status = 'cancelled';
					}

					// 刷新当前列表
					this.loadMockData();

					hideLoading();
					showToast('订单已取消', 'success');
					this.cancelOrderId = '';
				}, 1000);
			},

			// 去支付
			async payOrder(orderId, totalAmount) {
				showLoading('正在获取支付参数...');

				// 模拟支付流程
				setTimeout(() => {
					hideLoading();
					uni.showModal({
						title: '模拟支付',
						content: `订单号: ${orderId}, 金额: ${totalAmount}元`,
						confirmText: '支付成功',
						cancelText: '支付失败',
						success: (res) => {
							if (res.confirm) {
								// 支付成功
								const orderIndex = this.mockOrders.findIndex(o => o.id ===
								orderId);
								if (orderIndex !== -1) {
									this.mockOrders[orderIndex].status = 'paid';
								}

								showToast('支付成功', 'success');
								// 刷新订单列表
								this.loadMockData();
							} else {
								showToast('支付已取消');
							}
						}
					});
				}, 1000);
			},

			// 去点餐
			goToMenu() {
				uni.switchTab({
					url: '/pages/menu/menu'
				});
			},

			// 获取订单状态文本
			getStatusText(status) {
				switch (status) {
					case orderStatus.PENDING_PAYMENT:
						return '待支付';
					case orderStatus.PAID:
						return '已支付';
					case orderStatus.COOKING:
						return '烹饪中';
					case orderStatus.COMPLETED:
						return '已完成';
					case orderStatus.CANCELLED:
						return '已取消';
					default:
						return '未知状态';
				}
			},

			// 获取订单状态样式类
			getStatusClass(status) {
				switch (status) {
					case orderStatus.PENDING_PAYMENT:
						return 'status-pending';
					case orderStatus.PAID:
						return 'status-paid';
					case orderStatus.COOKING:
						return 'status-cooking';
					case orderStatus.COMPLETED:
						return 'status-completed';
					case orderStatus.CANCELLED:
						return 'status-cancelled';
					default:
						return '';
				}
			},

			// 计算订单总商品数量
			getTotalItems(items) {
				if (!items || !items.length) return 0;
				return items.reduce((total, item) => total + item.quantity, 0);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.order-list-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		width: 100%;
		overflow: hidden;
		background-color: #f8f8f8;
		position: relative;
	}

	.header-bg {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 200rpx;
		background: linear-gradient(90deg, #fa436a, #F56C6C);
		border-radius: 0 0 40rpx 40rpx;
		z-index: 0;
	}

	.page-header {
		position: relative;
		z-index: 1;
		padding: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #fff;
	}

	.filter-tabs {
		display: flex;
		height: 80rpx;
		width: 100%;
		background-color: white;
	}



	.order-list {
		flex: 1;
		flex-shrink: 0;
		overflow-y: auto;
		margin-top: 20rpx;
		box-sizing: border-box;
		padding: 0 30rpx 30rpx;
	}

	.order-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 10rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.order-shop {
		display: flex;
		align-items: center;
	}

	.shop-icon {
		margin-right: 10rpx;
	}

	.shop-name {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.order-status {
		font-size: 26rpx;
		font-weight: bold;

		&.status-pending {
			color: #ff9900;
		}

		&.status-paid {
			color: #19be6b;
		}

		&.status-cooking {
			color: #19be6b;
		}

		&.status-completed {
			color: #19be6b;
		}

		&.status-cancelled {
			color: #999;
		}
	}

	.order-content {
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.goods-item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.goods-image {
		width: 100rpx;
		height: 100rpx;
		border-radius: 10rpx;
		margin-right: 20rpx;
		background-color: #f5f5f5;
	}

	.goods-info {
		flex: 1;
		overflow: hidden;
	}

	.goods-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 4rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.goods-spec {
		font-size: 24rpx;
		color: #999;
	}

	.goods-right {
		text-align: right;
		margin-left: 20rpx;
	}

	.goods-price {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 4rpx;
	}

	.goods-quantity {
		font-size: 24rpx;
		color: #999;
	}

	.order-summary {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx dashed #f5f5f5;
	}

	.order-time {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.order-amount {
		font-size: 28rpx;
		color: #333;
		display: flex;
		align-items: baseline;
	}

	.price-symbol {
		font-size: 24rpx;
		color: #fa436a;
	}

	.price-value {
		font-size: 32rpx;
		font-weight: bold;
		color: #fa436a;
	}

	.order-footer {
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: flex-end;
	}

	.order-btns {
		display: flex;

		.u-button {
			margin-left: 20rpx;
			border-radius: 30rpx;
		}
	}

	.no-data {
		padding: 200rpx 0 100rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.empty-action {
		margin-top: 40rpx;

		.u-button {
			border-radius: 40rpx;
		}
	}

	.loading-more {
		padding: 20rpx 0;
		text-align: center;
	}

	.order-btns u-button {
		margin: 0 10rpx !important;
	}

	.order-btns #u-wave-btn {
		margin: 0 10rpx !important;
	}

	
</style> 